package com.mirror.llk.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mirror.frame.log4j.ILog;
import com.mirror.frame.log4j.Logger;
import com.mirror.frame.service.BaseService;
import com.mirror.llk.bean.domain.TTheme;
import com.mirror.llk.bean.domain.TUser;
import com.mirror.llk.bean.request.ThemeListRequest;
import com.mirror.llk.bean.request.ThemePublishRequest;
import com.mirror.llk.bean.response.ThemeListResponse;
import com.mirror.llk.bean.response.ThemePublishResponse;
import com.mirror.llk.dao.ThemeDao;
import com.mirror.llk.dao.UserDao;
import com.mirror.llk.service.ThemeService;
import com.mirror.llk.util.CommonUtils;
import com.mirror.llk.util.ConfigCache;
import com.mirror.llk.util.Constant;
import com.mirror.llk.util.Interface;

@Service
public class ThemeServiceImpl extends BaseService implements ThemeService {

    @Logger
    private static ILog log;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ThemeDao themeDao;

    @Override
    public ThemePublishResponse publishTheme(ThemePublishRequest requestBean) {
        ThemePublishResponse response = null;
        TTheme theme = requestBean.getTheme();
        Long userId = theme.getUserId();
        // 保存新用户
        if (userId == null) {
            userId = userDao.saveUser(requestBean.getUser());
            theme.setUserId(userId);
        }
        // 保存新主题
        Long themeId = themeDao.saveTheme(theme);
        // 保存文件
        try {
            CommonUtils.generateFile(theme.getThemeImage(), ConfigCache.getRootPath(), Constant.APP_DIR.THEME, themeId + Constant.FILE_TYPE.ZIP);
            response = new ThemePublishResponse(themeId, userId);
            response.setResultCode(Interface.SUCCESS_CODE);
            response.setResultCode(Interface.ERROR_MESSAGE.get(Interface.SUCCESS_CODE));
        }
        catch (IOException e) {
            log.error("保存的主题文件失败", e);
            // 回滚保存的主题
            themeDao.deleteTheme(themeId);
            // 返回响应
            response = new ThemePublishResponse(null, userId);
            response.setResultCode(Interface.ERROR_CODE_1001);
            response.setResultCode(Interface.ERROR_MESSAGE.get(Interface.ERROR_CODE_1001));
        }
        return response;
    }

    @Override
    public ThemeListResponse listTheme(ThemeListRequest requestBean) {
        List<TUser> userList = new ArrayList<TUser>();
        List<TTheme> themeList = new ArrayList<TTheme>();
        List<Map<String, Object>> results = themeDao.listTheme(requestBean.getPage(), requestBean.getThemeType());
        for (Map<String, Object> result : results) {
            themeList.add(new TTheme((Long) result.get("id"), (String) result.get("themeName"), (String) result.get("themeDesc"), (Integer) result
                    .get("themeType"), (Long) result.get("themeDownload"), (Long) result.get("userId")));
            this.extractUser(result, userList);
        }
        return new ThemeListResponse(themeList, userList);
    }

    private void extractUser(Map<String, Object> result, List<TUser> userList) {
        Long userId = (Long) result.get("userId");
        if (!isUserExist(userId, userList)) {
            userList.add(new TUser(userId, (String) result.get("tencentId"), (String) result.get("sinaId"), (String) result.get("userNick"),
                    (String) result.get("regChannel")));
        }
    }

    private boolean isUserExist(Long userId, List<TUser> userList) {
        for (TUser user : userList) {
            if (userId.equals(user.getId())) {
                return true;
            }
        }
        return false;
    }
}
